package com.game.doudizhu.service;

import com.game.doudizhu.model.Player;
import com.game.doudizhu.model.AIPlayer;
import com.game.doudizhu.repository.PlayerRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.NoSuchElementException;

@Service
public class PlayerService {
    @Autowired
    private PlayerRepository playerRepository;
    
    public Player register(String username, String password) {
        // 检查用户名是否已存在
        if (playerRepository.existsByUsername(username)) {
            throw new RuntimeException("用户名已存在");
        }
        Player player = new Player();
        player.setUsername(username);
        player.setPassword(password);
        player.setScore(1000); // 初始积分
        player.setRegisterTime(LocalDateTime.now());
        return playerRepository.save(player);
    }
    
    public Player login(String username, String password) {
        return playerRepository.findByUsernameAndPassword(username, password)
                .orElseThrow(() -> new NoSuchElementException("用户名或密码错误"));
    }
    
    public Player getPlayer(Long id) {
        return playerRepository.findById(id)
                .orElseThrow(() -> new NoSuchElementException("玩家不存在，ID: " + id));
    }
    
    @Transactional
    public Player updatePlayer(Player player) {
        return playerRepository.save(player);
    }
    
    public List<Player> getAllPlayers() {
        return playerRepository.findAll();
    }
    
    public void deletePlayer(Long id) {
        if (!playerRepository.existsById(id)) {
            throw new NoSuchElementException("玩家不存在，ID: " + id);
        }
        playerRepository.deleteById(id);
    }
    
    public boolean existsById(Long id) {
        return playerRepository.existsById(id);
    }
    
    public Player findByUsername(String username) {
        return playerRepository.findByUsername(username)
                .orElse(null);  // 如果找不到返回 null
    }
    
    public boolean existsByUsername(String username) {
        return playerRepository.existsByUsername(username);
    }
    
    public Player findByUsernameAndPassword(String username, String password) {
        return playerRepository.findByUsernameAndPassword(username, password)
                .orElse(null);  // 如果找不到返回 null
    }

    // 获取在线玩家数量
    public int getOnlinePlayersCount() {
        // 实现获取在线玩家数量的逻辑
        return 0; // 临时返回
    }

    @Transactional
    public <T extends Player> T savePlayer(T player) {
        return playerRepository.save(player);
    }
}